<template>
  <view class="order-page">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <u-search v-model="userPhone" placeholder="搜索用户手机号" @search="handleSearch" @clear="handleClear" :show-action="false" height="60" bg-color="#f5f5f5" />
    </view>
    <!-- <view @click="okkkkk">允许</view> -->
    <!-- 标签页切换 -->

    <!-- 筛选器 -->
    <view class="filter-container" v-if="showFilter">
      <view class="filter-row">
        <view class="filter-item" @click="showPayStatusPicker = true">
          <text class="filter-label">支付状态</text>
          <u-input v-model="payStatusText" placeholder="请选择支付状态" :border="true" readonly suffix-icon="arrow-down" @click="showPayStatusPicker = true" />
        </view>

        <view class="filter-item" @click="showVerifyStatusPicker = true">
          <text class="filter-label">核销状态</text>
          <u-input v-model="verifyStatusText" placeholder="请选择核销状态" :border="true" readonly suffix-icon="arrow-down" @click="showVerifyStatusPicker = true" />
        </view>
      </view>

      <!-- 修改后的时间筛选 -->
      <view class="filter-row">
        <view class="filter-item">
          <text class="filter-label">支付时间</text>
          <view class="time-range-container">
            <input v-model="startTimeText" placeholder="开始时间" :border="true" readonly suffix-icon="calendar" @click="showStartTimePicker = true" />
            <text class="time-separator">至</text>
            <input v-model="endTimeText" placeholder="结束时间" :border="true" readonly suffix-icon="calendar" @click="showEndTimePicker = true" />
          </view>
        </view>
      </view>

      <view class="filter-actions">
        <u-button type="primary" size="small" @click="handleFilter" :loading="loading">筛选</u-button>
        <u-button type="default" size="small" @click="resetFilter">重置</u-button>
      </view>
    </view>

    <!-- 支付状态选择器 -->
    <u-picker :show="showPayStatusPicker" :columns="[payStatusList]" keyName="label" @confirm="onPayStatusChange" @cancel="showPayStatusPicker = false"></u-picker>

    <!-- 核销状态选择器 -->
    <u-picker :show="showVerifyStatusPicker" :columns="[verifyStatusList]" keyName="label" @confirm="onVerifyStatusChange" @cancel="showVerifyStatusPicker = false"></u-picker>
    <!-- 电话操作弹窗 -->
    <u-action-sheet :show="showPhoneActionSheet" :actions="phoneActions" title="选择操作" @close="showPhoneActionSheet = false" @select="onPhoneActionSelect"> </u-action-sheet>
    <!-- 开始时间选择器 -->
    <u-datetime-picker
      :show="showStartTimePicker"
      mode="date"
      ref="datetimePicker"
      :formatter="formatter"
      v-model="startTimeValue"
      :maxDate="endTimeValue || getCurrentDate()"
      @confirm="onStartTimeChange"
      @cancel="showStartTimePicker = false"
    />

    <!-- 结束时间选择器 -->

    <u-datetime-picker
      :show="showEndTimePicker"
      mode="date"
      ref="datetimePicker"
      :formatter="formatter"
      v-model="endTimeValue"
      :maxDate="endTimeValue || getCurrentDate()"
      @confirm="onEndTimeChange"
      @cancel="showEndTimePicker = false"
    />
    <!-- 筛选按钮 -->
    <view class="filter-toggle">
      <u-button type="default" size="small" @click="toggleFilter" :icon="showFilter ? 'arrow-up' : 'arrow-down'">
        {{ showFilter ? '收起筛选' : '展开筛选' }}
      </u-button>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view v-for="(orderDd, index) in orderList" :key="index" class="order-card">
        <!-- 订单头部信息 -->
        <view class="order-header">
          <view class="order-info">
            <text class="order-id"> {{ orderDd.ebMerActivityTicket && orderDd.ebMerActivityTicket.name ? orderDd.ebMerActivityTicket.name : orderDd.orderId }}</text>
            <text v-show="false" class="order-time">{{ hiddenPhoneNumber(orderDd.userPhone) }}</text>
          </view>
          <view class="order-status">
            <u-tag :text="getOrderTypeText(orderDd.shippingType)" :type="orderDd.shippingType == 2 ? 'primary' : 'warning'" size="mini" />
          </view>
        </view>
        <view class="user-info">
          <view class="user-details" style="display: flex; align-items: center">
            <text class="user-phone">所售商户:</text>
            <text class="user-name" style="color: red">{{ orderDd.dealEbMerName }}</text>
          </view>
        </view>
        <!-- 用户信息 -->
        <view class="user-info" @click="handleUserPhoneClick(orderDd.userPhone)">
          <u-avatar :src="''" size="60" :random="true" />
          <view class="user-details">
            <text class="user-name">{{ getLastChar(orderDd.nickname) }}</text>
            <text class="user-phone">{{ orderDd.userPhone }}</text>
          </view>
          <view class="user-details" style="font-size: 24rpx">
            <view>支付时间：</view>
            {{ orderDd.payTime || '未支付' }}</view
          >
          <u-icon name="arrow-right" class="phone-icon"></u-icon>
        </view>

        <!-- 商户信息 -->
        <!-- <view class="merchant-info" v-if="orderDd.merName">
          <text class="merchant-label">商户:</text>
          <text class="merchant-name">{{ orderDd.merName }}</text>
        </view> -->

        <!-- 订单详情 -->
        <view class="order-details">
          <view v-if="orderDd.ebMerActivityTicket && orderDd.ebMerActivityTicket.icon" style="display: flex; align-items: center; justify-content: space-between; width: 100%">
            <image style="width: 180rpx; height: 180rpx; border-radius: 10px" :src="imgurl + orderDd.ebMerActivityTicket.icon" mode="" />
            <view style="width: calc(100% - 200rpx)">
              <view class="detail-row">
                <text class="detail-label">商品总数:</text>
                <text class="detail-value">{{ orderDd.totalNum }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">单价:</text>
                <text class="detail-value">￥{{ Number(orderDd.totalPrice).toFixed(2) }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">商品总价:</text>
                <text class="detail-value">￥{{ Number(orderDd.totalPrice).toFixed(2) * orderDd.totalNum }}</text>
              </view>

              <view class="detail-row">
                <text class="detail-label">实付金额:</text>
                <text class="detail-value price-highlight">￥{{ Number(orderDd.payPrice).toFixed(2) }}</text>
              </view>
            </view>
          </view>
          <view v-else>
            <view class="detail-row">
              <text class="detail-label">商品总数:</text>
              <text class="detail-value">{{ orderDd.totalNum }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">单价:</text>
              <text class="detail-value">￥{{ Number(orderDd.totalPrice).toFixed(2) }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">实付金额:</text>
              <text class="detail-value price-highlight">￥{{ Number(orderDd.payPrice).toFixed(2) }}</text>
            </view>
          </view>
          <!-- <view class="detail-row">
            <text class="detail-label">手续费:</text>
            <text class="detail-value">￥{{ (Number(orderDd.payPrice) * 0.0023).toFixed(2) }}</text>
          </view> -->
        </view>
        <view class="action-buttons">
          <u-button type="primary" size="small" @click.stop="showOrderDetail(orderDd)">查看详情</u-button>
          <!-- <u-button type="error" size="small" @click.stop="handleRefund(orderDd)" v-if="orderDd.paid && !orderDd.refundStatus">申请退款</u-button> -->
        </view>
        <!-- 分账信息  0.0023-->
        <!-- <view class="split-info" v-if="orderDd.ebMerLsSplitting">
          <view class="split-row">
            <text class="split-label">分账状态:</text>
            <u-tag :text="orderDd.ebMerLsSplitting ? '已分账' : '未分账'" :type="orderDd.ebMerLsSplitting ? 'success' : 'warning'" size="mini" />
          </view>
          <view class="split-row" v-if="orderDd.ebMerLsSplitting">
            <text class="split-label">预估到账:</text>
            <text class="split-value">￥{{ (Number(orderDd.ebMerLsSplitting.amount * 0.01).toFixed(2) - (Number(orderDd.payPrice) * 0.0023).toFixed(2)).toFixed(2) }}</text>
          </view>
        </view> -->

        <!-- 状态标签 -->
        <!-- <view class="status-tags">
          <u-tag :text="orderDd.paid ? '已支付' : '未支付'" :type="orderDd.paid ? 'success' : 'error'" size="mini" />
          <u-tag :text="getRefundStatusText(orderDd.refundStatus)" :type="getRefundStatusType(orderDd.refundStatus)" size="mini" v-if="orderDd.refundStatus" />
        </view> -->

        <!-- 操作按钮 -->
        <!--  <view class="action-buttons">
          <u-button type="primary" size="small" @click.stop="showOrderDetail(orderDd)">查看详情</u-button>
          <u-button type="error" size="small" @click.stop="handleRefund(orderDd)" v-if="orderDd.paid && !orderDd.refundStatus">申请退款</u-button>
        </view> -->
      </view>

      <!-- 空状态 -->
      <u-empty v-if="!loading && orderList.length === 0" text="暂无订单数据" :show="true" />
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="orderList.length > 0">
      <u-loadmore :status="loadStatus" @loadmore="loadMore" :loading-text="'正在加载...'" :loadmore-text="'加载更多'" :nomore-text="'没有更多了'" />
    </view>

    <!-- 订单详情弹窗 -->
    <u-popup :show="showDetailModal" mode="bottom" :border-radius="20">
      <view class="detail-modal">
        <view class="modal-header">
          <text class="modal-title">订单详情</text>
          <u-icon name="close" @click.stop="closeDetailModal" />
        </view>

        <view class="modal-content" v-if="currentOrder">
          <!-- 基本信息 -->
          <view class="detail-section">
            <view class="info-item">
              <text class="info-label">订单号:</text>
              <text class="info-value">{{ currentOrder.orderId }}</text>
            </view>

            <view class="info-item">
              <text class="info-label">支付时间:</text>
              <text class="info-value">{{ currentOrder.payTime || '未支付' }}</text>
            </view>
            <!-- <view class="info-item">
              <text class="info-label">支付方式:</text>
              <text class="info-value">{{ currentOrder.payType || '-' }}</text>
            </view> -->
          </view>

          <!-- 用户信息 -->
          <view class="detail-section">
            <view class="section-title">水卡信息</view>
            <view class="info-item">
              <text class="info-label">用户姓名:</text>
              <text class="info-value">{{ currentOrder.name || '' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">联系电话:</text>
              <u-tooltip :text="currentOrder.phone || ''" overlay> </u-tooltip>
            </view>
            <view class="info-item">
              <text class="info-label">水卡号:</text>
              <u-tooltip :text="currentOrder.cardNum || ''" overlay> </u-tooltip>
            </view>
            <view class="info-item">
              <text class="info-label">详细地址:</text>
              <u-tooltip :text="currentOrder.address || ''" overlay> </u-tooltip>
            </view>
          </view>

          <!-- 金额信息 -->
          <view class="detail-section">
            <view class="section-title">金额信息</view>
            <!-- <view class="status-tags">
              <u-tag :text="currentOrder.paid ? '已支付' : '未支付'" :type="currentOrder.paid ? 'success' : 'error'" size="mini" />
              <u-tag :text="getRefundStatusText(currentOrder.refundStatus)" :type="getRefundStatusType(currentOrder.refundStatus)" size="mini" v-if="currentOrder.refundStatus" />
            </view> -->
            <view class="info-item">
              <text class="info-label">商品总价:</text>
              <text class="info-value">￥{{ Number(currentOrder.totalPrice).toFixed(2) * currentOrder.totalNum }}</text>
            </view>
            <view class="info-item" v-if="currentOrder.deductionPrice">
              <text class="info-label">抵扣金额:</text>
              <text class="info-value">￥{{ Number(currentOrder.deductionPrice).toFixed(2) }}</text>
            </view>
            <view class="info-item" v-if="currentOrder.ebMerLsSplitting">
              <text class="info-label">用户实付:</text>
              <text class="info-value">￥{{ Number(currentOrder.payPrice).toFixed(2) }}</text>
            </view>
            <!--  <view class="info-item" v-if="currentOrder.ebMerLsSplitting">
              <text class="info-label">手续费:</text>
              <text class="info-value">￥{{ (Number(currentOrder.payPrice) * 0.0023).toFixed(2) }}</text>
            </view> -->
            <view class="info-item" v-if="currentOrder.ebMerLsSplitting">
              <text class="info-label">分账金额:</text>
              <text class="info-value">￥{{ Number(currentOrder.ebMerLsSplitting.wtAmount * 0.01).toFixed(2) }}</text>
            </view>

            <view class="info-item" v-if="currentOrder.ebMerLsSplitting">
              <text class="info-label">商户预估到账:</text>
              <text class="info-value price-highlight"
                >￥{{ (Number(currentOrder.ebMerLsSplitting.amount * 0.01).toFixed(2) - (Number(currentOrder.payPrice) * 0.0023).toFixed(2)).toFixed(2) }}</text
              >
            </view>
            <view class="info-item" v-if="currentOrder.ebMerLsSplitting">
              <text class="info-label">供应商预估到账:</text>
              <text class="info-value price-highlight">￥{{ Number(currentOrder.ebMerLsSplitting.waterAmount * 0.01).toFixed(2) }}</text>
            </view>
            <!-- <view class="info-item" v-if="currentOrder.couponPrice">
              <text class="info-label">优惠券金额:</text>
              <text class="info-value">￥{{ Number(currentOrder.couponPrice).toFixed(2) }}</text>
            </view> -->
          </view>
          <!-- 送货上门信息 -->
          <view class="detail-section" v-if="currentOrder.shippingType == '1'">
            <view class="section-title">送货上门信息</view>
            <view class="info-item">
              <text class="info-label">用户姓名:</text>
              <text class="info-value">{{ currentOrder.realName }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">联系电话:</text>
              <u-tooltip :text="currentOrder.userPhone" overlay> </u-tooltip>
            </view>
            <view class="info-item">
              <text class="info-label">详细地址:</text>
              <view style="word-wrap: break-word; white-space: normal; width: calc(100% - 160rpx); font-size: 26rpx">{{ currentOrder.userAddress }} </view>
            </view>
          </view>
          <!-- 其他信息 -->
          <view class="detail-section" v-if="currentOrder.clerkId || currentOrder.gainIntegral">
            <view class="section-title">其他信息</view>
            <view class="info-item" v-if="currentOrder.clerkId">
              <text class="info-label">店员/核销员:</text>
              <text class="info-value">{{ currentOrder.clerkId }}</text>
            </view>
            <view class="info-item" v-if="currentOrder.gainIntegral">
              <text class="info-label">赠送积分:</text>
              <text class="info-value">{{ currentOrder.gainIntegral }}</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 退款弹窗 -->
    <u-popup :show="showRefundModal" mode="center" width="80%" :border-radius="10">
      <view class="refund-modal">
        <view class="modal-header">
          <text class="modal-title">申请退款</text>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">退款金额:</text>
            <u-input v-model="refundForm.amount" type="number" placeholder="请输入退款金额" :border="true" />
          </view>
          <view class="form-item">
            <text class="form-label">退款原因:</text>
            <u-textarea v-model="refundForm.reason" placeholder="请输入退款原因" :border="true" :max-length="200" />
          </view>
        </view>
        <view class="modal-actions">
          <u-button type="default" @click="closeRefundModal">取消</u-button>
          <u-button type="primary" @click="confirmRefund" :loading="refundLoading">确认退款</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
/*订单列表,立即退款 */
import { listOrder, orderRefundApi } from '../../utils/merorder/mer.js';
import { IMG_URL } from '../../config/index.js';
export default {
  name: 'OrderManagement',
  data() {
    return {
      imgurl: IMG_URL,
      // 时间选择器相关状态 - 修改部分
      showStartTimePicker: false,
      showEndTimePicker: false,
      startTimeValue: Number(new Date()), // 开始时间值
      endTimeValue: Number(new Date()), // 结束时间值
      startTimeText: '', // 开始时间显示文本
      endTimeText: '', // 结束时间显示文本

      // 原有状态保持不变
      showVerifyStatusPicker: false,
      showPayStatusPicker: false,
      userPhone: '',

      // 是否显示筛选器
      showFilter: false,

      // 筛选参数 - 修改时间相关字段
      filterParams: {
        paid: 1,
        hasVerification: '',
        payTimeStart: '',
        payTimeEnd: ''
      },

      // 支付状态列表
      payStatusList: [
        { label: '全部', value: '' },
        { label: '待付款', value: 0 },
        { label: '已支付', value: 1 }
      ],

      // 核销状态列表
      verifyStatusList: [
        { label: '全部', value: '' },
        { label: '已核销', value: 1 },
        { label: '未核销', value: 2 },
        { label: '非核销订单', value: 0 }
      ],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderType: '9',
        payTimeStart: '',
        payTimeEnd: '',
        merId: '',
        paid: 1
      },

      // 订单列表
      orderList: [],

      // 加载状态
      loading: false,
      loadStatus: 'loadmore',

      // 总数
      total: 0,

      // 详情弹窗
      showDetailModal: false,
      currentOrder: '',

      // 退款弹窗
      showRefundModal: false,
      refundLoading: false,
      refundForm: {
        amount: '',
        reason: ''
      },
      currentRefundOrder: '',
      // 添加电话操作相关状态
      showPhoneActionSheet: false,
      currentPhoneNumber: '',
      phoneActions: [
        {
          name: '拨打',
          color: '#2979ff',
          fontSize: 32
        },
        {
          name: '复制',
          color: '#333',
          fontSize: 32
        }
      ]
    };
  },

  computed: {
    // 支付状态文本
    payStatusText() {
      const item = this.payStatusList.find((item) => item.value === this.filterParams.paid);
      return item ? item.label : '请选择支付状态';
    },

    // 核销状态文本
    verifyStatusText() {
      const item = this.verifyStatusList.find((item) => item.value === this.filterParams.hasVerification);
      return item ? item.label : '请选择核销状态';
    }
  },
  onReady() {
    // 微信小程序需要用此写法
    this.$refs.datetimePicker.setFormatter(this.formatter);
  },
  onLoad() {
    var userInfo = uni.getStorageSync('userInfo');
    this.queryParams.merId = userInfo && userInfo.merId ? userInfo.merId : '';
    if (this.queryParams.merId == '1751873058997917') {
      this.queryParams.merId = '';
    }
    this.getOrderList();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.queryParams.pageNum = 1;
    this.orderList = [];
    this.getOrderList().then(() => {
      uni.stopPullDownRefresh();
    });
  },

  // 触底加载
  onReachBottom() {
    this.loadMore();
  },

  methods: {
    // 处理用户电话点击
    handleUserPhoneClick(phoneNumber) {
      if (!phoneNumber) {
        uni.showToast({
          title: '暂无电话号码',
          icon: 'none'
        });
        return;
      }

      this.currentPhoneNumber = phoneNumber;
      this.showPhoneActionSheet = true;
    },

    // 电话操作选择
    onPhoneActionSelect(item) {
      this.showPhoneActionSheet = false;

      if (item.name === '拨打') {
        uni.makePhoneCall({
          phoneNumber: this.currentPhoneNumber
        });
      } else if (item.name === '复制') {
        uni.setClipboardData({
          data: this.currentPhoneNumber,
          success: () => {
            uni.showToast({
              title: '已复制到剪贴板',
              icon: 'success'
            });
          }
        });
      }
    },
    okkkkk() {
      this.Subscribe();
    },
    Subscribe() {
      uni.requestSubscribeMessage({
        //此处填写刚才申请模板的模板ID
        tmplIds: ['wrAxCn8qGigDFtECBBxrSwOsS9KpLsiw-ksw22RoS9A'],
        success(res) {
          console.log('@@@@@@@@@@@@@@@@@@@', res);
        },
        fail(res) {
          console.log('@@@@@@@@@@@@@@@@@@@', res);
        }
      });
    },
    /* 用户名截取 */
    getLastChar(str) {
      if (!str) return '-';
      const lastChar = str.charAt(str.length - 1);
      const maskedPart = '*'.repeat(str.length - 1);
      return `${maskedPart}${lastChar}`;
    },
    // 隐藏手机号中间四位的方法
    hiddenPhoneNumber(phone) {
      if (!phone) return '-';
      return phone.slice(0, 3) + '****' + phone.slice(7);
    },

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    // 获取当前日期
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 格式化日期显示
    formatDateText(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 开始时间选择确认 - 修改方法
    onStartTimeChange(value) {
      console.log('开始时间选择:', value);
      this.startTimeValue = value.value;
      this.startTimeText = this.formatDateText(value.value);
      this.filterParams.payTimeStart = this.startTimeText;
      this.showStartTimePicker = false;

      // 如果开始时间大于结束时间，清空结束时间
      if (this.endTimeValue && new Date(value.value) > new Date(this.endTimeValue)) {
        this.endTimeValue = '';
        this.endTimeText = '';
        this.filterParams.payTimeEnd = '';
      }
    },

    // 结束时间选择确认 - 修改方法
    onEndTimeChange(value) {
      console.log('结束时间选择:', value);
      this.endTimeValue = value.value;
      this.endTimeText = this.formatDateText(value.value);
      this.filterParams.payTimeEnd = this.endTimeText;
      this.showEndTimePicker = false;
    },

    // 获取订单列表
    async getOrderList() {
      if (this.loading) return;

      this.loading = true;
      this.loadStatus = 'loading';

      try {
        // 这里调用你的API接口
        const res = await listOrder(this.queryParams);

        if (this.queryParams.pageNum === 1) {
          this.orderList = res.rows || [];
        } else {
          this.orderList = [...this.orderList, ...(res.rows || [])];
        }

        this.total = res.total || 0;

        // 判断是否还有更多数据
        if (this.orderList.length >= this.total) {
          this.loadStatus = 'nomore';
        } else {
          this.loadStatus = 'loadmore';
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        uni.showToast({
          title: '获取订单列表失败',
          icon: 'none'
        });
        this.loadStatus = 'loadmore';
      } finally {
        this.loading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.queryParams.userPhone = this.userPhone;
      this.orderList = [];
      this.getOrderList();
    },

    // 清空搜索
    handleClear() {
      this.userPhone = '';
      this.queryParams.userPhone = '';
      this.queryParams.pageNum = 1;
      this.orderList = [];
      this.getOrderList();
    },

    // 切换筛选器显示
    toggleFilter() {
      this.showFilter = !this.showFilter;
    },

    // 支付状态改变
    onPayStatusChange(value) {
      this.filterParams.paid = value.value[0].value;
      this.showPayStatusPicker = false;
    },

    // 核销状态改变
    onVerifyStatusChange(value) {
      this.filterParams.hasVerification = value.value[0].value;
      this.showVerifyStatusPicker = false;
    },

    // 应用筛选
    handleFilter() {
      this.queryParams = {
        ...this.queryParams,
        ...this.filterParams,
        pageNum: 1
      };
      this.orderList = [];
      this.getOrderList();
    },

    // 重置筛选 - 修改方法
    resetFilter() {
      this.filterParams = {
        paid: 1,
        hasVerification: '',
        payTimeStart: '',
        payTimeEnd: ''
      };

      // 重置时间相关状态
      this.startTimeValue = Number(new Date());
      this.endTimeValue = Number(new Date());
      this.startTimeText = '';
      this.endTimeText = '';

      this.handleFilter();
    },

    // 加载更多
    loadMore() {
      if (this.loadStatus !== 'loadmore' || this.loading) return;

      this.queryParams.pageNum += 1;
      this.getOrderList();
    },

    // 显示订单详情
    showOrderDetail(orderDd) {
      this.currentOrder = orderDd;
      if (this.currentOrder && this.currentOrder.remark) {
        this.currentOrder.name = orderDd.remark.split('-')[0];
        this.currentOrder.phone = orderDd.remark.split('-')[1];
        this.currentOrder.cardNum = orderDd.remark.split('-')[2] || '';
        this.currentOrder.address = orderDd.remark.split('-')[3];
      }
      this.showDetailModal = true;
    },

    // 关闭详情弹窗
    closeDetailModal() {
      this.showDetailModal = false;
      this.currentOrder = '';
    },

    // 处理退款
    handleRefund(orderDd) {
      this.currentRefundOrder = orderDd;
      this.refundForm = {
        amount: orderDd.payPrice,
        reason: ''
      };
      this.showRefundModal = true;
    },

    // 关闭退款弹窗
    closeRefundModal() {
      this.showRefundModal = false;
      this.currentRefundOrder = '';
      this.refundForm = {
        amount: '',
        reason: ''
      };
    },

    // 确认退款
    async confirmRefund() {
      if (!this.refundForm.amount) {
        uni.showToast({
          title: '请输入退款金额',
          icon: 'none'
        });
        return;
      }

      if (!this.refundForm.reason) {
        uni.showToast({
          title: '请输入退款原因',
          icon: 'none'
        });
        return;
      }

      this.refundLoading = true;

      try {
        // 调用退款API
        await orderRefundApi({
          orderId: this.currentRefundOrder.orderId,
          amount: this.refundForm.amount,
          reason: this.refundForm.reason
        });

        uni.showToast({
          title: '退款申请成功',
          icon: 'success'
        });

        this.closeRefundModal();

        // 刷新列表
        this.queryParams.pageNum = 1;
        this.orderList = [];
        this.getOrderList();
      } catch (error) {
        console.error('退款失败:', error);
        uni.showToast({
          title: '退款申请失败',
          icon: 'none'
        });
      } finally {
        this.refundLoading = false;
      }
    },

    // 获取订单类型文本
    getOrderTypeText(orderType) {
      const typeMap = {
        1: '送货上门',
        2: '自提'
      };
      return typeMap[orderType] || '未知类型';
    },

    // 获取核销状态文本
    getVerifyStatusText(status) {
      const statusMap = {
        0: '非核销订单',
        1: '已核销',
        2: '未核销'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取核销状态类型
    getVerifyStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'warning'
      };
      return typeMap[status] || 'info';
    },

    // 获取退款状态文本
    getRefundStatusText(status) {
      const statusMap = {
        0: '未退款',
        1: '申请中',
        2: '已退款',
        3: '退款中'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取退款状态类型
    getRefundStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'error'
      };
      return typeMap[status] || 'info';
    }
  }
};
</script>

<style lang="scss" scoped>
// 订单管理页面样式
.order-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20rpx;
}

// 搜索栏
.search-bar {
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

// 标签页容器
.tabs-container {
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 80rpx;
  z-index: 99;
  height: 35px;
  line-height: 35px;
}

// 筛选器
.filter-container {
  background-color: #fff;
  padding: 20rpx;
  border-bottom: 1px solid #eee;
  animation: slideDown 0.3s ease-out;

  .filter-row {
    display: flex;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .filter-item {
      flex: 1;
      margin-right: 20rpx;

      &:last-child {
        margin-right: 0;
      }

      .filter-label {
        display: block;
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
        font-weight: 500;
      }

      // 新增时间范围容器样式
      .time-range-container {
        display: flex;
        align-items: center;
        gap: 10rpx;

        .time-separator {
          font-size: 24rpx;
          color: #999;
          padding: 0 5rpx;
          white-space: nowrap;
        }

        .u-input {
          flex: 1;
        }
      }
    }
  }

  .filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
    margin-top: 30rpx;
    padding-top: 20rpx;
    border-top: 1px solid #f0f0f0;
  }
}

// 筛选切换按钮
.filter-toggle {
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  text-align: center;
}

// 订单列表
.order-list {
  padding: 0 20rpx;
  margin-top: 20rpx;
}

// 订单卡片
.order-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.12);
  }

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 6rpx;
    height: 100%;
    // background: linear-gradient(135deg, #2979ff, #40a9ff);
    background: linear-gradient(135deg, #2979ff, #ffffff);
  }
}

// 订单头部
.order-header {
  width: calc(100% - 20rpx);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1px solid #f5f5f5;

  .order-info {
    flex: 1;

    .order-id {
      display: block;
      font-size: 32rpx;
      // font-weight: 600;
      color: #333;
      margin-bottom: 8rpx;
      // letter-spacing: 0.5rpx;
    }

    .order-time {
      font-size: 24rpx;
      color: #999;
    }
  }

  .order-status {
    margin-left: 20rpx;
  }
}

// 用户信息
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 16rpx;
  background-color: #fafafa;
  border-radius: 12rpx;

  .user-details {
    margin-left: 20rpx;
    flex: 1;

    .user-name {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 6rpx;
      font-weight: 500;
    }

    .user-phone {
      font-size: 24rpx;
      color: #666;
    }
  }
}

// 商户信息
.merchant-info {
  margin-bottom: 20rpx;
  padding: 12rpx 16rpx;
  background-color: #f0f9ff;
  border-radius: 8rpx;
  border-left: 4rpx solid #2979ff;

  .merchant-label {
    font-size: 26rpx;
    color: #666;
    font-weight: 500;
  }

  .merchant-name {
    font-size: 26rpx;
    color: #333;
    margin-left: 10rpx;
    font-weight: 600;
  }
}

// 订单详情
.order-details {
  width: 100%;
  margin-bottom: 20rpx;
  // padding: 16rpx;
  background-color: #fafafa;
  border-radius: 12rpx;

  .detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;

    &:last-child {
      margin-bottom: 0;
      padding-top: 8rpx;
      border-top: 1px solid #eee;
    }

    .detail-label {
      font-size: 26rpx;
      color: #666;
    }

    .detail-value {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;

      &.price-highlight {
        color: #ff4757;
        font-weight: 700;
        font-size: 30rpx;
      }
    }
  }
}

// 分账信息
.split-info {
  margin-bottom: 20rpx;
  padding: 16rpx;
  background-color: #f6ffed;
  border-radius: 12rpx;
  border: 1px solid #d9f7be;

  .split-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .split-label {
      font-size: 26rpx;
      color: #666;
    }

    .split-value {
      font-size: 26rpx;
      color: #52c41a;
      font-weight: 600;
    }
  }
}

// 状态标签
.status-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

// 操作按钮
.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding-top: 16rpx;
  border-top: 1px solid #f0f0f0;
}

// 加载更多
.load-more {
  padding: 40rpx 20rpx;
}

// 详情弹窗
.detail-modal {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 30rpx 20rpx;
    border-bottom: 1px solid #eee;
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 10;

    .modal-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .modal-content {
    flex: 1;
    padding: 20rpx 30rpx 30rpx;
  }

  .detail-section {
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 20rpx;
      padding-bottom: 10rpx;
      border-bottom: 2rpx solid #2979ff;
      display: inline-block;
    }

    .info-item {
      // width: calc(100% - 80rpx);
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 16rpx 0;
      border-bottom: 1px solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .info-label {
        font-size: 28rpx;
        color: #666;
        min-width: 160rpx;
        font-weight: 500;
      }

      .info-value {
        font-size: 28rpx;
        color: #333;
        flex: 1;
        text-align: right;
        word-break: break-all;

        &.price-highlight {
          color: #ff4757;
          font-weight: 700;
          font-size: 32rpx;
        }
      }
    }
  }
}

// 退款弹窗
.refund-modal {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;

  .modal-header {
    padding: 30rpx 30rpx 20rpx;
    border-bottom: 1px solid #eee;
    text-align: center;

    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .modal-content {
    padding: 30rpx;

    .form-item {
      margin-bottom: 30rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 12rpx;
        font-weight: 500;
      }
    }
  }

  .modal-actions {
    display: flex;
    padding: 20rpx 30rpx 30rpx;
    gap: 20rpx;

    .u-button {
      flex: 1;
    }
  }
}

// 动画效果
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

// 响应式适配
@media screen and (max-width: 750rpx) {
  .filter-row {
    flex-direction: column;

    .filter-item {
      margin-right: 0;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .order-details .detail-row {
    font-size: 24rpx;

    .detail-value.price-highlight {
      font-size: 28rpx;
    }
  }

  .action-buttons {
    flex-direction: column;
    gap: 12rpx;
  }
}

// 暗黑模式适配（可选）
@media (prefers-color-scheme: dark) {
  .order-page {
    background-color: #1a1a1a;
  }

  .search-bar,
  .tabs-container,
  .filter-container,
  .filter-toggle,
  .order-card,
  .detail-modal {
    background-color: #2a2a2a;
    border-color: #444;
  }

  .order-card {
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.3);
  }

  .order-id,
  .user-name,
  .merchant-name,
  .detail-value,
  .modal-title,
  .section-title,
  .info-value,
  .form-label {
    color: #fff;
  }

  .order-time,
  .user-phone,
  .merchant-label,
  .detail-label,
  .info-label {
    color: #ccc;
  }

  .user-info,
  .order-details {
    background-color: #333;
  }

  .merchant-info {
    background-color: #1e3a5f;
  }

  .split-info {
    background-color: #1f2f1f;
    border-color: #4a5c4a;
  }
}
</style>
